package cn.ejiakanghu.logistics.service.impl;

import cn.com.ejiakanghu.core.exceptions.BizException;
import cn.ejiakanghu.logistics.service.GoodsRejectedService;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;

import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.shop.ChainLockPickup;
import org.linlinjava.litemall.db.vo.shop.MedicalLockPickup;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：sujp
 * @date ：Created in 2021/11/10 15:55
 * @description：退货
 * @modified By：
 * @version: 1.0
 */
@Service
public class GoodsRejectedServiceImpl extends LogisticBusiBaseServiceImpl implements GoodsRejectedService {
    @Resource
    private LogisticsBaseServiceAbstractImpl logisticsBaseServiceAbstract;
    @Resource
    private AgedmallLgReceiveOrderMapper agedmallLgReceiveOrderMapper;
    @Resource
    private AgedmallLgMissionMapper agedmallLgMissionMapper;
    @Resource
    private AgedmallLgBaseInfoMapper agedmallLgBaseInfoMapper;
    @Resource
    private AgedmallGoodsEquMapper agedmallGoodsEquMapper;
    @Resource
    private AgedmallLgRfidGoodsCurStatMapper agedmallLgRfidGoodsCurStatMapper;
    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;
    @Resource
    private LitemallOrderMapper litemallOrderMapper;
    @Resource
    private AgedmallLgGoodsSignForRecordMapper agedmallLgGoodsSignForRecordMapper;
    @Resource
    private LogisticBusiBaseServiceImpl logisticBusiBaseServiceImpl;
    @Resource
    private AgedmallLgMissionManRecordMapper agedmallLgMissionManRecordMapper;

    /**
     * 退货取货及换货数据新增及修改
     *
     * @param missionId
     * @param imgs
     * @param missionIsOver
     * @param lgStat
     */
    @Override
    public boolean pickupIsCompleteOrReturnIsComplete(Integer missionId, List<String> imgs, int missionIsOver, int lgStat) {
        //新增 busireceiveorder busiimg  baseInfo当前物流状态 业务是否结束更新   mission表的状态更新
        //根据missionId更新物流信息
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(missionIsOver);
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());

        List<ChainLockPickup> chainLockPickups = checkChainIsFinish(agedmallLgBaseInfo.getLgContent());
        //判断是否有软链，如果有，是否已经全部归还
        if (chainLockPickups != null && !chainLockPickups.isEmpty()) {
            for (ChainLockPickup chain : chainLockPickups) {
                if (chain.getPickUpStatus() != 3) {
                    return false;
                }
            }
            //更新软链rfid状态
            List<Long> goodsEquList = new ArrayList<>();
            List<String> chainRfidList = new ArrayList<>();
            chainLockPickups.forEach(chain -> {
                goodsEquList.add(Long.parseLong(chain.getEquId()));
                chainRfidList.add(chain.getEquId());
            });
            AgedmallGoodsEquExample goodsEquExample = new AgedmallGoodsEquExample();
            goodsEquExample.or().andTypeEqualTo(0).andEquIdIn(goodsEquList);
            AgedmallGoodsEqu goodsEqu = new AgedmallGoodsEqu();

            AgedmallLgRfidGoodsCurStatExample goodsCurStatExample = new AgedmallLgRfidGoodsCurStatExample();
            goodsCurStatExample.or().andTypeEqualTo(1).andRfidIn(chainRfidList);
            AgedmallLgRfidGoodsCurStat goodsCurStat = new AgedmallLgRfidGoodsCurStat();
            goodsEqu.setDistributionType(0);
            agedmallGoodsEquMapper.updateByExampleSelective(goodsEqu, goodsEquExample);
            agedmallLgRfidGoodsCurStatMapper.updateByExampleSelective(goodsCurStat, goodsCurStatExample);
        }


        List<MedicalLockPickup> medicalLockPickups = checkCabinetIsFinish(agedmallLgBaseInfo.getLgContent());
        //判断是否有医柜锁，如果有，是否已经全部归还
        if (!medicalLockPickups.isEmpty()) {
            for (MedicalLockPickup cabinet : medicalLockPickups) {
                if (cabinet.getState() != 2) {
                    return false;
                }
            }
        }

        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);
        //更新状态
        List<Integer> missionList = new ArrayList<>();
        //修改当前baseInfo状态 LgBaseInfoStatConstant.BACKING_GOODS
        Integer baseInfoState = lgStat;
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(lgMission.getId().longValue(), null, lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 2);
        //保存拍照上传的图片
        //插入img表
        if (imgs.size() != 0) {
            String url = base64ToUrl(imgs);
            if (StrUtil.isBlank(url)) {
                logger.error("图片转换错误：{}", url);
                throw new BizException("图片转换错误");
            }
            insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
        }
        //修改baseInfo状态
        agedmallLgBaseInfo.setLgStat(baseInfoState);
        agedmallLgBaseInfo.setLgIsOver(BaseInfoIsOverEnum.END.getCode());
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        //同步修改orderGoods状态
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), baseInfoState);

        //更新签收表
        List<Integer> orderGoodsId = getorderGoodsIds(agedmallLgBaseInfo.getLgContent());
        LitemallOrderGoods orderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(orderGoodsId.get(0));
        LitemallOrder order = litemallOrderMapper.selectByPrimaryKey(orderGoods.getOrderId());
        for (int j = 0; j < orderGoodsId.size(); j++) {
            AgedmallLgGoodsSignForRecord goodsSignForRecord = new AgedmallLgGoodsSignForRecord();
            goodsSignForRecord.setCreatedTime(LocalDateTime.now());
            goodsSignForRecord.setLgBaseInfoId(agedmallLgBaseInfo.getId());
            goodsSignForRecord.setState(1);
            goodsSignForRecord.setGoodsId(orderGoodsId.get(j).longValue());
            goodsSignForRecord.setSignForTime(LocalDateTime.now());
            goodsSignForRecord.setOrderCode(order.getOrderSn());
            goodsSignForRecord.setUserType(1);
            agedmallLgGoodsSignForRecordMapper.insertSelective(goodsSignForRecord);
        }


            //List<Integer> missionBackstage = logisticBusiBaseServiceImpl.createMissionBackstage(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.MAINTAIN.getCode());

            //退货完成创建维护任务
            missionList = createMissionBackstage(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.MAINTAIN.getCode());
            AgedmallLgMissionManRecordExample agedmallLgMissionManRecordExample = new AgedmallLgMissionManRecordExample();
            agedmallLgMissionManRecordExample.or().andBaseInfoIdEqualTo(agedmallLgBaseInfo.getId()).andMissionTypeEqualTo(LogisticsMissionTypeEnum.MAINTAIN.getCode());
            //agedmallLgMissionManRecordExample.setOrderByClause("`id` DESC");
            //未使用
            //agedmallLgMissionManRecordExample.or().andIsUseEqualTo(0);
            AgedmallLgMissionManRecord agedmallLgMissionManRecord = agedmallLgMissionManRecordMapper.selectOneByExampleSelective(agedmallLgMissionManRecordExample);
            //接单
            receiveOrderEvent(agedmallLgMissionManRecord.getManId().intValue(),missionList.get(0),null);
            agedmallLgMissionManRecord.setIsUse(1);
            //物流 -手动分配配货配送人员记录表 改为已使用状态
            agedmallLgMissionManRecordMapper.updateByPrimaryKey(agedmallLgMissionManRecord);
        return true;
    }

    /**
     * 创建退货开始任务
     *
     * @param orderCode
     * @param baseInfoId
     */
    @Override
    public List<Integer> createRejectedMission(String orderCode, Integer baseInfoId) {
        List<Integer> missionIds = new ArrayList<>();
        int type = LogisticsMissionTypeEnum.RETURN.getCode();
        //退货
        if (orderCode != null) {
            //批量的插入
            missionIds = logisticsBaseServiceAbstract.insertIntoMissonByOrderCode(orderCode, type);
        } else if (baseInfoId != null) {
            //单个的插入
            missionIds = logisticsBaseServiceAbstract.insertIntoOneMission(baseInfoId, type);
        }
        return missionIds;
    }


    /**
     * 取件中
     *
     * @param manId
     * @param missionId
     * @param messageType
     * @param receiveType
     * @param execType
     */
    @Override
    public void inReturnPickup(Integer manId, Integer missionId, Integer messageType, Integer receiveType, Integer execType) {
        logisticsBaseServiceAbstract.logisticsEventInProgress(manId, missionId, messageType, receiveType, execType);
        //logisticsBaseServiceAbstract.updateMissionMissionIsOver(missionId, LogisticsMissionTypeEnum.RETURN.getCode());
    }

    /**
     * 退货取货完成事件
     *
     * @param missionId
     * @param imgs      图片集合
     */
    @Override
    public void pickupIsComplete(Integer missionId, List<String> imgs) {
        pickupIsCompleteOrReturnIsComplete(missionId, imgs, LgMissionIsOverEum.END.getCode(), LgBaseInfoStatConstant.BACK_GOODS_COMPLETE);

    }


    /**
     * 退货完成
     *
     * @param missionId 任务表任务id
     * @param imgs      图片的集合
     */
    @Override
    public boolean goodsReturnCompleted(Integer missionId, List<String> imgs) {
       return pickupIsCompleteOrReturnIsComplete(missionId, imgs, LgMissionIsOverEum.END.getCode(), LgBaseInfoStatConstant.BACK_GOODS_COMPLETE);
    }
}
